// index.js
const app = getApp()

Page({
  data: {
    transactions: [
      {
        id: 1,
        type: 'expense',
        categoryName: '餐饮',
        amount: '68.00',
        date: '2024-01-15',
        note: '午餐'
      },
      {
        id: 2,
        type: 'expense',
        categoryName: '交通',
        amount: '15.00',
        date: '2024-01-15',
        note: '地铁'
      },
      {
        id: 3,
        type: 'income',
        categoryName: '工资',
        amount: '5000.00',
        date: '2024-01-10',
        note: '1月工资'
      },
      {
        id: 4,
        type: 'expense',
        categoryName: '购物',
        amount: '299.00',
        date: '2024-01-08',
        note: '新衣服'
      }
    ]
  },

  onLoad: function() {
    // 页面加载时执行
    this.loadTransactions()
  },

  onShow: function() {
    // 页面显示时执行，用于刷新数据
    this.loadTransactions()
  },

  loadTransactions: function() {
    // 从本地存储加载交易记录
    const transactions = wx.getStorageSync('transactions') || this.data.transactions
    this.setData({
      transactions: transactions
    })

    // 计算总收入和支出
    this.calculateTotals()
  },

  calculateTotals: function() {
    // 实际应用中应该按月份筛选
    let totalExpense = 0
    let totalIncome = 0

    this.data.transactions.forEach(item => {
      if (item.type === 'expense') {
        totalExpense += parseFloat(item.amount)
      } else {
        totalIncome += parseFloat(item.amount)
      }
    })

    this.setData({
      totalExpense: totalExpense.toFixed(2),
      totalIncome: totalIncome.toFixed(2)
    })
  },

  navigateToAdd: function() {
    wx.navigateTo({
      url: '/pages/add/add'
    })
  }
})
